const handleBlogRouter = require("./src/router/blog.js");
const {handelUserRouter,getCookieExpires} = require("./src/router/user");
const querystring = require("querystring");
const {get,set} = require('./src/db/redis');
const {access} = require('./src/utils/log');

//sessin 数据
// const SESSIN_DATA = {}
const getPostData = (req) => {
    const promise1 = new Promise((resolve,reject)=>{
        if(req.method != "POST"){
            resolve({});
            return;
        }
        
        if(req.headers['content-type']!= "application/json"){
            resolve({});
            return;
        }
        let postData = "";
        req.on("data",chunk=>{
            postData += chunk;
        
        })
        req.on("end",()=>{
            
            if(!postData){
                resolve({});
                return;
            }
           
            resolve(JSON.parse(postData) );
        })
    })
    return promise1;
}
const serverHandle = (req,res)=>{
    //记录access log 
    access(`${req.method} -- ${req.url} -- ${req.headers['user-agent']} -- ${Date.now()}`)
    res.setHeader("content-type","application/json");
    const url = req.url;
    req.path = url.split("?")[0];
    //解析query
    req.query = querystring.parse(url.split("?")[1]);
    
    //解析cookie
    req.cookie = {};
    const cookieStr = req.headers.cookie || '';
    cookieStr.split(";").forEach(item => {
        if(!item){
            return;
        }
        const arr = item.split("=");
        const key = arr[0];
        const val = arr[1];
        req.cookie[key] = val;
     
    });
    //解析sessin
    // let needSetCookie = false;
    // let userId = req.cookie.userid;
    // if(userId){
        
    //     if(!SESSIN_DATA[userId]){
    //         SESSIN_DATA[userId] = {};
    //     }

    // }else{
    //     needSetCookie = true;
    //     userId = `${Date.now()}_${Math.random()}`;
    //     SESSIN_DATA[userId] = {};
    // }
    // req.sessin = SESSIN_DATA[userId];
    // console.log('hello',req.sessin)
    // console.log('shi',SESSIN_DATA[userId])
    //处理postData
    //解析sessin 使用 redis
    let needSetCookie = false;
    let userId = req.cookie.userid;
    if(!userId){
        needSetCookie = true;
        userId = `${Date.now()}_${Math.random()}`;
        //初始化redis 中的session值
        set(userId,{});
    }
    //获取session
    req.sessionId = userId;
    get(req.sessionId).then(sessionData=>{
        if(sessionData === null){
            //初始化redis 中的session值
            set(req.sessionId,{});
            //设置session 
            req.session = {}
        }else{
            //设置session 
            req.session = sessionData;
        }
        
        return getPostData(req)
    })
    .then(postData=>{
        req.body = postData;
        
        //处理blog路由
        const blogResult = handleBlogRouter(req,res);
        if(blogResult){
           
            blogResult.then(blogData=>{
                if(needSetCookie){
                    res.setHeader("Set-Cookie",`userid=${userId}; path=/; httpOnly;expires=${getCookieExpires()}`);
                }
                res.end(JSON.stringify(blogData))
            })
            return;
        }
        
       
        
        //处理user路由
        // const userData = handelUserRouter(req,res);
        // if(userData){
        //     res.end(
        //         JSON.stringify(userData)
        //     )
        //     return;
        // }
        const userResult = handelUserRouter(req,res);
        if(userResult){
            userResult.then(userData=>{
                if(needSetCookie){
                    res.setHeader("Set-Cookie",`userid=${userId}; path=/; httpOnly;expires=${getCookieExpires()}`);
                }
                res.end(JSON.stringify(userData));
                
            })
            return;
        }
       
       //未命中路由返回404
        res.writeHead(404,{"Content-type":"text/plain"});
        res.write("404 not found\n")
        res.end();
    })
    
    
    
    
}
module.exports = serverHandle;